import paho.mqtt.client as mqtt

from components.mqtt.base import MQTT_USERNAME, MQTT_PASSWORD, MQTT_SERVER, MQTT_PUBLISH_CLIENT_ID


def connect_mqtt():
    def on_connect(client, userdata, flags, reason_code, properties):
        if reason_code == 0:
            pass
        else:
            publish_client.reconnect()

    publish_client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, MQTT_PUBLISH_CLIENT_ID)
    publish_client.on_connect = on_connect
    publish_client.username_pw_set(MQTT_USERNAME, MQTT_PASSWORD)
    publish_client.connect(MQTT_SERVER, 1883)
    return publish_client


def publish(data):
    client = connect_mqtt()
    client.loop_start()
    client.publish(data['topic'], payload=data['data'])
    client.disconnect()


# publish(data={'topic': '/News/Topic/news', 'data': '{"orgId": 2,"msgType": "new_order", "orderNo": "12312312312"}'})
